﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data.SqlServerCe;

namespace AioApp.Bll
{

    public class Util
    {
        private static Util instance;

        private Util() { }

        public static Util Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Util();
                }
                return instance;
            }
        }
        public string getMD5(string passwordParam )
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string password;
            byte[] bs = System.Text.Encoding.UTF8.GetBytes( passwordParam);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            password = s.ToString();


            return password;
        }

        public bool Login(string email, string password)
        {
            SqlCeConnection conn;
            bool ret = false;
            string connectionString = AioApp.Properties.Settings.Default.aiodbConnectionString;
            
            conn = new SqlCeConnection(connectionString);

            conn.Open();

            SqlCeCommand command = new SqlCeCommand("SELECT * FROM USUARIO WHERE EMAIL = @EMAIL", conn);
            command.Parameters.Add("EMAIL", email);

            SqlCeDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                string passwordBd = reader["password"].ToString();
                string formMDS = Bll.Util.Instance.getMD5(password);
                string bdMD5 = Bll.Util.Instance.getMD5(passwordBd);
                if (passwordBd == password)
                {
                    ret = true;
                }
            }

            conn.Close();
            conn.Dispose();

            return ret;
        }
    }

}